<template>
  <div>
    <el-form
      :model="form"
      label-width="100px"
      label-position="left"
    >
      <el-form-item label="文章标题">
        <el-input v-model="form.title" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="文章摘要">
        <el-input v-model="form.subTitle" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="小图">
        <img-upload v-model="form.content" :previewStyle="{width: '100px', height: '100px'}"></img-upload>
      </el-form-item>
      <el-form-item label="文章链接">
        <el-input v-model="form.linkUrl" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item label="排序权重">
        <el-input-number v-model="form.sort"></el-input-number>
      </el-form-item>
      <el-form-item label="选择分组">
        <el-select v-model="form.gid">
          <el-option
            v-for="item in groupList"
            :key="item.gid"
            :label="item.name"
            :value="item.gid"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <hr>
      <el-button type="primary" class="long-btn" @click="save">保 存</el-button>
    </el-form>
  </div>
</template>

<script>
import * as apis from 'services/articles'
import { ImgUpload } from 'components'

export default {
  name: 'ArticlesListEdit',
  components: {
    ImgUpload,
  },
  data() {
    return {
      form: {
        title: '',
        linkUrl: '',
        sort: 0,
        gid: 0,
        content: '',
        subTitle: '',
      },
      groupList: [],
    }
  },
  created() {
    const { id } = this.$route.query
    if (id) {
      this.getInfo(id)
      this.form.id = id
    }
    this.getArticlesGroup()
  },
  methods: {
    getArticlesGroup() {
      apis.getArticlesGroup()
        .then((data) => {
          const ary = data
          ary.unshift({
            gid: 0,
            name: '未分组',
          })
          this.groupList = ary
        })
    },
    getInfo(id) {
      apis.getArticleInfo(id)
        .then((data) => {
          this.form = data
        })
    },
    save() {
      apis.saveArticles(this.form)
        .then(() => {
          this.$message({
            type: 'success',
            message: '保存成功!',
          })
          this.form = {
            title: '',
            linkUrl: '',
            sort: 0,
            gid: 0,
          }
          this.$router.push('/articlesList')
        })
        .catch(() => {
          this.$message({
            type: 'error',
            message: '保存失败',
          })
        })
    },
  },
}
</script>

<style>

</style>
